import os
import sys

def concatenate_and_add_column(key_file, output_file):
    """
    Reads a key file, concatenates tab-delimited files from adjusted paths,
    and adds a concatenated 6th column (key column 2 + input column 4) to the output.

    Args:
        key_file (str): Path to the key tab-delimited file.
        output_file (str): Path to the output file.
    """
    try:
        # Read the key file to extract adjusted paths and 2nd column values
        with open(key_file, 'r') as kf:
            entries = []
            for line in kf:
                columns = line.strip().split('\t')
                if len(columns) >= 3:
                    # Adjust the path to include "/Final/BC_Corrected_Collapse_Location_Sort.txt"
                    adjusted_path = os.path.join(columns[2], "Final", "BC_Corrected_Collapse_Location_Sort.txt")
                    entries.append((adjusted_path, columns[1]))  # (adjusted path, value for 6th column)

        # Open the output file for writing
        with open(output_file, 'w') as outfile:
            for filepath, key_value in entries:
                if not os.path.isfile(filepath):
                    print(f"File not found: {filepath}", file=sys.stderr)
                    continue

                # Read the input file line by line
                with open(filepath, 'r') as infile:
                    for line in infile:
                        columns = line.strip().split('\t')
                        if len(columns) >= 4:
                            # Concatenate key_value with the 4th column of the input file
                            new_column = f"{key_value}_{columns[3]}"
                            # Write all columns plus the new column to the output file
                            outfile.write('\t'.join(columns + [new_column]) + '\n')

        print(f"Files concatenated and modified successfully into {output_file}")

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py <key_file> <output_file>")
        sys.exit(1)

    key_file = sys.argv[1]
    output_file = sys.argv[2]
    concatenate_and_add_column(key_file, output_file)
